package utility

import (
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
)

// 预定义错误码
const (
	CodeSuccess      = 10000 // 成功返回
	CodeLoginInvalid = 10001 // 登录失效
	CodeValidation   = 10002 // 验证错误
	CodeForbidden    = 10003 // 权限禁止
	CodeLoginFailed  = 10004 // 登录失败
	CodeOperation    = 10005 // 操作失败
	CodeBlacklist    = 10007 // 黑名单
	CodeBanned       = 10008 // 账户被禁
)

// 错误码映射
var codeMsgMap = map[int]string{
	CodeSuccess:      "成功返回",
	CodeLoginInvalid: "登录失效",
	CodeValidation:   "验证错误",
	CodeForbidden:    "权限禁止",
	CodeLoginFailed:  "登录失败",
	CodeOperation:    "操作失败",
	CodeBlacklist:    "黑名单",
	CodeBanned:       "账户被禁",
}

// Response 基础响应结构
type Response struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

// PaginatedResponse 分页响应结构
type PaginatedResponse struct {
	Response
	Limit int `json:"limit"`
	Total int `json:"total"`
	Page  int `json:"page"`
}

// Success 成功响应
func Success(data interface{}, msg ...string) *Response {
	message := "成功返回"
	if len(msg) > 0 {
		message = msg[0]
	}
	return &Response{
		Code:    CodeSuccess,
		Message: message,
		Data:    data,
	}
}

// SuccessWithPagination 分页成功响应
func SuccessWithPagination(data interface{}, limit, total int, msg ...string) *PaginatedResponse {
	message := "成功返回"
	if len(msg) > 0 {
		message = msg[0]
	}
	return &PaginatedResponse{
		Response: Response{
			Code:    CodeSuccess,
			Message: message,
			Data:    data,
		},
		Limit: limit,
		Total: total,
	}
}

// GetCodeFromError 从错误中获取错误码
func GetCodeFromError(err error) int {
	return gerror.Code(err).Code()
}

// Error 错误处理核心方法
func Error(code int, err ...error) error {
	msg := getDefaultMessage(code)
	if len(err) > 0 {
		return gerror.WrapCode(gcode.New(code, "", nil), err[0], msg)
	}
	return gerror.NewCode(gcode.New(code, "", nil), msg)
}

// ErrorResponse 错误响应
func ErrorResponse(code int, msg string) *Response {
	if msg == "" {
		msg = codeMsgMap[code]
	}
	return &Response{
		Code:    code,
		Message: msg,
		Data:    nil,
	}
}

// Code 获取错误码
func Code(err error) int {
	return gerror.Code(err).Code()
}

// getDefaultMessage 私有方法：获取默认错误消息
func getDefaultMessage(code int) string {
	messages := map[int]string{
		CodeSuccess:      "成功返回",
		CodeLoginInvalid: "登录失效",
		CodeValidation:   "参数验证失败",
		CodeForbidden:    "无权访问",
		CodeLoginFailed:  "登录失败",
		CodeOperation:    "操作失败",
	}
	return messages[code]
}
